/*
 * Copyright (c) 2014.
 * 游戏服务器核心代码编写人陈磊拥有使用权
 * 联系方式：E-mail:13638363871@163.com ;qq:502959937
 * 个人博客主页：http://my.oschina.net/chenleijava
 */

package nettyProxyEngine4;

import io.netty.buffer.Unpooled;
import io.netty.channel.*;

/**
 * @author 石头哥哥 </br>
 *         dcServer1.7 </br>
 *         Date:14-2-24 </br>
 *         Time:下午3:47 </br>
 *         Package:{@link nettyProxyEngine4}</br>
 *         Comment：   proxy  - game  server         handler
 */
public class ProxyBackenServerHandler extends ChannelInboundHandlerAdapter {

    private final Channel client_proxy_channel;

    public ProxyBackenServerHandler(Channel client_proxy_channel) {
        this.client_proxy_channel = client_proxy_channel;
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.read();
        ctx.write(Unpooled.EMPTY_BUFFER);
    }


    /**
     * Adds the specified listener to this future.  The
     * specified listener is notified when this future is
     * {@linkplain # isDone() done}.  If this future is already
     * completed, the specified listener is notified immediately.
     * Calls {@link io.netty.channel.ChannelHandlerContext#fireChannelRead(Object)} to forward
     * to the next {@link io.netty.channel.ChannelInboundHandler} in the {@link io.netty.channel.ChannelPipeline}.
     *
     * Sub-classes may override this method to change behavior.
     *  将游戏服务器中的数据推送到客户端
     */
    @Override
    public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
        client_proxy_channel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    //to next read
                    ctx.channel().read();
                } else {
                    future.channel().close();
                }
            }
        });
    }

    /**
     * Calls {@link io.netty.channel.ChannelHandlerContext#fireChannelInactive()} to forward
     * to the next {@link io.netty.channel.ChannelInboundHandler} in the {@link io.netty.channel.ChannelPipeline}.
     *
     * Sub-classes may override this method to change behavior.
     *
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        ProxyFrontendServerHandler.closeOnFlush(client_proxy_channel);
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ProxyFrontendServerHandler.closeOnFlush(ctx.channel());        //proxy_server_channel
    }

}
